package com.tfswue.hql.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.tfswue.hql.common.Result;
import com.tfswue.hql.entity.Order;
import com.tfswue.hql.entity.User;
import com.tfswue.hql.exception.BusinessException;
import com.tfswue.hql.mapper.OrderMapper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.util.List;

@Slf4j
@Service
public class OrderService {
    
    @Autowired
    private OrderMapper orderMapper;
    
    @Autowired
    private RestTemplate restTemplate;
    
    public Order getOrderById(Long id) {
        try {
            Order order = orderMapper.selectById(id);
            if (order != null) {
                // 调用用户服务获取用户信息
                try {
                    Result<User> userResult = restTemplate.getForObject("http://user-server/api/user/" + order.getUserId(), Result.class);
                    if (userResult != null && userResult.getCode() == 200 && userResult.getData() != null) {
                        // 这里需要手动转换，因为RestTemplate返回的是LinkedHashMap
                        // 在实际项目中，建议使用Feign客户端来处理这种情况
                        log.info("成功获取用户信息，用户ID: {}", order.getUserId());
                    }
                } catch (Exception e) {
                    log.warn("获取用户信息失败，用户ID: {}, 错误: {}", order.getUserId(), e.getMessage());
                    // 即使用户服务调用失败，也返回订单信息
                }
            }
            return order;
        } catch (Exception e) {
            log.error("查询订单失败，订单ID: {}", id, e);
            throw new BusinessException("查询订单失败");
        }
    }
    
    public List<Order> getAllOrders() {
        try {
            return orderMapper.selectList(null);
        } catch (Exception e) {
            log.error("查询所有订单失败", e);
            throw new BusinessException("查询订单列表失败");
        }
    }
    
    public List<Order> getOrdersByUserId(Long userId) {
        try {
            QueryWrapper<Order> queryWrapper = new QueryWrapper<>();
            queryWrapper.eq("user_id", userId);
            return orderMapper.selectList(queryWrapper);
        } catch (Exception e) {
            log.error("根据用户ID查询订单失败，用户ID: {}", userId, e);
            throw new BusinessException("查询用户订单失败");
        }
    }
    
    public Order createOrder(Order order) {
        try {
            int result = orderMapper.insert(order);
            if (result > 0) {
                log.info("订单创建成功，订单ID: {}", order.getId());
                return order;
            } else {
                throw new BusinessException("订单创建失败");
            }
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("创建订单失败", e);
            throw new BusinessException("创建订单失败");
        }
    }
    
    public Order updateOrder(Order order) {
        try {
            // 先检查订单是否存在
            Order existingOrder = orderMapper.selectById(order.getId());
            if (existingOrder == null) {
                return null;
            }
            
            int result = orderMapper.updateById(order);
            if (result > 0) {
                log.info("订单更新成功，订单ID: {}", order.getId());
                return orderMapper.selectById(order.getId());
            } else {
                throw new BusinessException("订单更新失败");
            }
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("更新订单失败，订单ID: {}", order.getId(), e);
            throw new BusinessException("更新订单失败");
        }
    }
    
    public boolean deleteOrder(Long id) {
        try {
            // 先检查订单是否存在
            Order existingOrder = orderMapper.selectById(id);
            if (existingOrder == null) {
                return false;
            }
            
            int result = orderMapper.deleteById(id);
            if (result > 0) {
                log.info("订单删除成功，订单ID: {}", id);
                return true;
            } else {
                throw new BusinessException("订单删除失败");
            }
        } catch (BusinessException e) {
            throw e;
        } catch (Exception e) {
            log.error("删除订单失败，订单ID: {}", id, e);
            throw new BusinessException("删除订单失败");
        }
    }
}